package cn.hill4j.tool.spring.ext.dispatcher;

import cn.hill4j.tool.spring.ext.dispatcher.exception.DispatchRegisterException;
import cn.hill4j.tool.spring.ext.dispatcher.exception.DispatchRouteNoFoundException;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
  * ClassName: DestinationFactory
  * Description: 分发目标处理器工厂
  * @author hillchen
  * Date 2023/8/8
  * @version: 1.0
  */
public class DestinationFactory {
    private DestinationFactory(){};
    private static Map<DispatchRoute, DsMethodHandler> HANDLER_MAP = new ConcurrentHashMap<>();
    /**
     * @author hillchen
     * Description: 根据分发路由注册分发执行处理器
     * Date 2023/8/8 23:45
     * @param dispatchRoute 分发路由
     * @param handler 分发执行处理器
     **/
    static void registerStrategy(DispatchRoute dispatchRoute, DsMethodHandler handler){
        if (HANDLER_MAP.containsKey(dispatchRoute)){
            throw new DispatchRegisterException(String.format("[group:%s,biz:%s]处理器注册，不能重复注册",dispatchRoute.getGroupName(),dispatchRoute.getBizName()));
        }
        HANDLER_MAP.putIfAbsent(dispatchRoute, handler);
    }
    /**
     * @author hillchen
     * Description: 根据分发路由获取分发执行处理器
     * Date 2023/8/8 23:46
     * @param dispatchRoute 分发路由
     * @return DsMethodHandler 分发执行处理器
     **/
    public static DsMethodHandler selectHandler(DispatchRoute dispatchRoute){
        if (!HANDLER_MAP.containsKey(dispatchRoute)){
            throw new DispatchRouteNoFoundException(String.format("[group:%s,biz:%s]处理器未找到",dispatchRoute.getGroupName(),dispatchRoute.getBizName()));
        }
        return HANDLER_MAP.get(dispatchRoute);
    }
}
